package cn.lds.j375.chlm.service.impl;

import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.User;
import cn.lds.j375.chlm.mapper.UserMapper;
import cn.lds.j375.chlm.service.UserService;
import cn.lds.j375.chlm.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.Objects;

public class UserServiceImpl implements UserService {

    private static SqlSession sqlSession;

    private static UserMapper userMapper;

    static {
        sqlSession = SqlSessionUtil.getSqlSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }




    @Override
    public ResultDTO<User> selectUserById(Integer id) {

        User user = userMapper.selectUserById(1);

        if (Objects.isNull(user)){
            return ResultDTO.buildError();
        }


        return ResultDTO.buildSuccess(user);
    }

    @Override
    public ResultDTO<User> loginUser(User user) {

        User loginUser = userMapper.loginUser(user);

        if (Objects.isNull(loginUser)){
            return ResultDTO.buildError("用户名或密码错");
        }
        return ResultDTO.buildSuccess(loginUser);
    }

    @Override
    public ResultDTO regUser(User user) {

        try {
            int i = userMapper.regUser(user);

            if (i <= 0){
    //            sqlSession.rollback();
                return ResultDTO.buildError("注册不成功");
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }


        return ResultDTO.buildSuccess();
    }

    @Override
    public ResultDTO modifyUser(User user) {

        try {
            int i = userMapper.modifyUser(user);

            if (i <= 0){
    //            sqlSession.rollback();
                return ResultDTO.buildError("用户修改失败");
            }

            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }

        return ResultDTO.buildSuccess();
    }
}
